import React, { useState, useCallback } from 'react'
import {
    View,
    Alert,
    TouchableOpacity,
    Image,
    PermissionsAndroid,
    Platform,
    ActivityIndicator,
} from 'react-native'
import { launchCamera, launchImageLibrary, ImagePickerResponse, ImageLibraryOptions, CameraOptions } from 'react-native-image-picker'
import { Icon, Text } from '@rneui/themed'
import { useUpload } from '../hooks/useUpload'
import ImagePreviewModal from './ImagePreviewModal'

export interface UploadedImage {
    id?: string
    uri: string
    url?: string
    name: string
    size: number
    type?: string
    uploading?: boolean
    uploadProgress?: number
}

interface ImageUploaderProps {
    images: UploadedImage[]
    onImagesChange: (images: UploadedImage[] | ((prevImages: UploadedImage[]) => UploadedImage[])) => void
    maxImages?: number
    maxSize?: number // 单位：MB
    allowedFormats?: string[]
    showPreview?: boolean
    imageSize?: number // 图片显示尺寸
    style?: any
    directory?: string // 上传目录
    autoUpload?: boolean // 是否自动上传
    onUploadedUrlsChange?: (files: { url: string, name: string, size: number }[]) => void // 上传完成的文件列表变化回调
}

export const ImageUploader: React.FC<ImageUploaderProps> = ({
    images = [],
    onImagesChange,
    maxImages = 5,
    maxSize = 1, // 1MB
    allowedFormats = ['.jpg', '.jpeg', '.png'],
    showPreview = true,
    imageSize = 80,
    style,
    directory,
    autoUpload = true,
    onUploadedUrlsChange
}) => {
    const [showImagePreview, setShowImagePreview] = useState(false)
    const [previewImage, setPreviewImage] = useState<{url: string, name: string} | null>(null)
    const { uploadFile } = useUpload(directory)

    // 请求相机权限
    const requestCameraPermission = useCallback(async () => {
        if (Platform.OS === 'android') {
            try {
                // 检查是否已经有权限
                const hasPermission = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.CAMERA)
                if (hasPermission) {
                    return true
                }

                // 请求权限
                const granted = await PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.CAMERA,
                    {
                        title: '相机权限',
                        message: '需要相机权限来拍照，请在设置中允许应用使用相机',
                        buttonNeutral: '稍后询问',
                        buttonNegative: '取消',
                        buttonPositive: '确定',
                    }
                )

                if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                    return true
                } else if (granted === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
                    // 用户选择了"不再询问"，引导用户去设置页面
                    Alert.alert(
                        '权限被拒绝',
                        '相机权限被拒绝，请在设置中手动开启相机权限',
                        [
                            { text: '取消', style: 'cancel' },
                            {
                                text: '去设置',
                                onPress: () => {
                                    console.log('引导用户去设置页面')
                                }
                            }
                        ]
                    )
                    return false
                } else {
                    return false
                }
            } catch (err) {
                console.warn('请求相机权限失败:', err)
                return false
            }
        }
        return true
    }, [])

    // 请求存储权限（用于访问相册）
    const requestStoragePermission = useCallback(async () => {
        if (Platform.OS === 'android') {
            try {
                // Android 13+ 使用 READ_MEDIA_IMAGES
                if (Platform.Version >= 33) {
                    const hasPermission = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES)
                    if (hasPermission) {
                        return true
                    }

                    const granted = await PermissionsAndroid.request(
                        PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES,
                        {
                            title: '相册权限',
                            message: '需要相册权限来访问图片，请在设置中允许应用访问相册',
                            buttonNeutral: '稍后询问',
                            buttonNegative: '取消',
                            buttonPositive: '确定',
                        }
                    )
                    return granted === PermissionsAndroid.RESULTS.GRANTED
                } else {
                    // Android 13 以下版本使用 READ_EXTERNAL_STORAGE
                    const hasPermission = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE)
                    if (hasPermission) {
                        return true
                    }

                    const granted = await PermissionsAndroid.request(
                        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                        {
                            title: '存储权限',
                            message: '需要存储权限来访问相册，请在设置中允许应用访问存储',
                            buttonNeutral: '稍后询问',
                            buttonNegative: '取消',
                            buttonPositive: '确定',
                        }
                    )
                    return granted === PermissionsAndroid.RESULTS.GRANTED
                }
            } catch (err) {
                console.warn('请求存储权限失败:', err)
                return false
            }
        }
        return true
    }, [])

    // 验证图片格式和大小
    const validateImage = useCallback((uri: string, size: number, fileName: string) => {
        // 检查文件大小
        const maxSizeBytes = maxSize * 1024 * 1024
        if (size > maxSizeBytes) {
            Alert.alert('图片过大', `图片大小不能超过${maxSize} MB`)
            return false
        }

        // 检查文件格式
        const fileExtension = fileName.toLowerCase().substring(fileName.lastIndexOf('.'))
        if (!allowedFormats.includes(fileExtension)) {
            Alert.alert('格式不支持', `只支持 ${allowedFormats.join('、')} 格式的图片`)
            return false
        }

        return true
    }, [maxSize, allowedFormats])

    // 上传图片到服务器
    const uploadImageToServer = useCallback(async (image: UploadedImage) => {
        if (!autoUpload) return image

        try {
            // 更新上传状态
            onImagesChange(prevImages => {
                const updatedImages = prevImages.map(img =>
                    img.id === image.id ? { ...img, uploading: true, uploadProgress: 0 } : img
                )
                console.log('开始上传，更新状态:', updatedImages)
                return updatedImages
            })

            // 上传文件
            const serverUrl = await uploadFile({
                uri: image.uri,
                type: image.type || 'image/jpeg',
                name: image.name,
                size: image.size
            })

            // 更新图片信息，添加服务器URL
            onImagesChange(prevImages => {
                const finalImages = prevImages.map(img =>
                    img.id === image.id
                        ? { ...img, url: serverUrl, uploading: false, uploadProgress: 100 }
                        : img
                )
                console.log('上传完成，服务器URL:', serverUrl)
                console.log('更新后的图片列表:', finalImages)
                
                // 通知上传完成的文件列表变化
                if (onUploadedUrlsChange) {
                    const uploadedFiles = finalImages
                        .filter(img => !!img.url)
                        .map(img => ({ url: img.url!, name: img.name, size: img.size }))
                    onUploadedUrlsChange(uploadedFiles)
                }
                
                return finalImages
            })

            return { ...image, url: serverUrl, uploading: false, uploadProgress: 100 }
        } catch (error) {
            console.error('上传图片失败:', error)

            // 更新失败状态
            onImagesChange(prevImages => {
                const failedImages = prevImages.map(img =>
                    img.id === image.id ? { ...img, uploading: false, uploadProgress: 0 } : img
                )
                console.log('上传失败，更新状态:', failedImages)
                return failedImages
            })

            Alert.alert('上传失败', '图片上传失败，请重试')
            throw error
        }
    }, [autoUpload, onImagesChange, uploadFile, onUploadedUrlsChange])

    // 拍照功能
    const handleTakePhoto = useCallback(async () => {
        const hasPermission = await requestCameraPermission()
        if (!hasPermission) {
            Alert.alert('权限不足', '需要相机权限才能拍照')
            return
        }

        const options: CameraOptions = {
            mediaType: 'photo',
            quality: 0.8,
            maxWidth: 1920,
            maxHeight: 1080,
            saveToPhotos: true,
            includeBase64: false,
        }

        try {
            const response: ImagePickerResponse = await launchCamera(options)

            if (response.didCancel) {
                console.log('用户取消拍照')
                return
            }

            if (response.errorCode) {
                Alert.alert('拍照失败', response.errorMessage || '未知错误')
                return
            }

            if (response.assets && response.assets.length > 0) {
                const asset = response.assets[0]
                if (asset.uri) {
                    const fileName = asset.fileName || `photo_${Date.now()}.jpg`
                    const fileSize = asset.fileSize || 0

                    // 验证图片
                    if (validateImage(asset.uri, fileSize, fileName)) {
                        const newImage: UploadedImage = {
                            id: Date.now().toString(),
                            uri: asset.uri,
                            url: asset.uri,
                            name: fileName,
                            size: fileSize,
                            type: asset.type || 'image/jpeg',
                            uploading: false,
                            uploadProgress: 0
                        }

                        // 先添加到列表
                        const updatedImages = [...images, newImage]
                        onImagesChange(updatedImages)

                        // 如果启用自动上传，立即上传
                        if (autoUpload) {
                            uploadImageToServer(newImage).catch(console.error)
                        }
                    }
                }
            }
        } catch (error) {
            console.error('拍照错误:', error)
            Alert.alert('拍照失败', '拍照过程中发生错误')
        }
    }, [requestCameraPermission, validateImage, images, onImagesChange, autoUpload, uploadImageToServer])

    // 从相册选择
    const handleChooseFromLibrary = useCallback(async () => {
        // 检查存储权限
        const hasStoragePermission = await requestStoragePermission()
        if (!hasStoragePermission) {
            Alert.alert('权限不足', '需要存储权限才能访问相册')
            return
        }

        const options: ImageLibraryOptions = {
            mediaType: 'photo',
            quality: 0.8,
            maxWidth: 1920,
            maxHeight: 1080,
            includeBase64: false,
            selectionLimit: maxImages - images.length, // 限制选择数量
        }

        try {
            const response: ImagePickerResponse = await launchImageLibrary(options)

            if (response.didCancel) {
                console.log('用户取消选择')
                return
            }

            if (response.errorCode) {
                Alert.alert('选择失败', response.errorMessage || '未知错误')
                return
            }

            if (response.assets && response.assets.length > 0) {
                const validImages = response.assets
                    .filter(asset => asset.uri)
                    .filter(asset => {
                        const fileName = asset.fileName || `gallery_${Date.now()}.png`
                        const fileSize = asset.fileSize || 0
                        return validateImage(asset.uri!, fileSize, fileName)
                    })
                    .map(asset => ({
                        id: `${Date.now()}_${Math.random()}`,
                        uri: asset.uri!,
                        url: asset.uri!,
                        name: asset.fileName || `gallery_${Date.now()}.png`,
                        size: asset.fileSize || 0,
                        type: asset.type || 'image/jpeg',
                        uploading: false,
                        uploadProgress: 0
                    }))

                if (validImages.length > 0) {
                    // 先添加到列表
                    const updatedImages = [...images, ...validImages]
                    onImagesChange(updatedImages)

                    // 如果启用自动上传，批量上传
                    if (autoUpload) {
                        validImages.forEach(image => {
                            uploadImageToServer(image).catch(console.error)
                        })
                    }
                }
            }
        } catch (error) {
            console.error('选择图片错误:', error)
            Alert.alert('选择失败', '选择图片过程中发生错误')
        }
    }, [requestStoragePermission, validateImage, images, onImagesChange, maxImages, autoUpload, uploadImageToServer])

    // 处理图片上传
    const handleImageUpload = useCallback(() => {
        Alert.alert(
            '选择图片',
            '请选择图片来源',
            [
                {
                    text: '取消',
                    style: 'cancel',
                },
                {
                    text: '拍照',
                    onPress: handleTakePhoto,
                },
                {
                    text: '从相册选择',
                    onPress: handleChooseFromLibrary,
                },
            ]
        )
    }, [handleTakePhoto, handleChooseFromLibrary])

    // 移除图片
    const removeImage = useCallback((index: number) => {
        const newImages = images.filter((_, i) => i !== index)
        onImagesChange(newImages)
    }, [images, onImagesChange])

    // 手动重试上传
    const retryUpload = useCallback((image: UploadedImage) => {
        uploadImageToServer(image).catch(console.error)
    }, [uploadImageToServer])

    // 预览图片
    const handleImagePreview = useCallback((uri: string, name: string) => {
        if (showPreview) {
            setPreviewImage({ url: uri, name })
            setShowImagePreview(true)
        }
    }, [showPreview])

    // 获取文件大小显示文本
    const getFileSizeText = useCallback((size: number) => {
        if (size < 1024) {
            return `${size}B`
        } else if (size < 1024 * 1024) {
            return `${(size / 1024).toFixed(1)}KB`
        } else {
            return `${(size / (1024 * 1024)).toFixed(1)}MB`
        }
    }, [])

    return (
        <View style={[{ marginTop: 8 }, style]}>
            {/* 已上传的图片列表 */}
            {images.length > 0 && (
                <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12, marginBottom: 16 }}>
                    {images.map((image, index) => (
                        <View key={index} style={{ position: 'relative', width: imageSize, height: imageSize }}>
                            <TouchableOpacity
                                onPress={() => handleImagePreview(image.url || image.uri, image.name)}
                                disabled={!showPreview || image.uploading}
                            >
                                <Image
                                    source={{ uri: image.url || image.uri }}
                                    style={{
                                        width: imageSize,
                                        height: imageSize,
                                        borderRadius: 8,
                                        backgroundColor: '#f5f5f5',
                                        opacity: image.uploading ? 0.6 : 1
                                    }}
                                    resizeMode="cover"
                                />

                                {/* 上传状态指示器 */}
                                {image.uploading && (
                                    <View style={{
                                        position: 'absolute',
                                        top: 0,
                                        left: 0,
                                        right: 0,
                                        bottom: 0,
                                        backgroundColor: 'rgba(0,0,0,0.5)',
                                        borderRadius: 8,
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                    }}>
                                        <ActivityIndicator size="small" color="#fff" />
                                        <Text style={{ color: '#fff', fontSize: 10, marginTop: 4 }}>
                                            上传中...
                                        </Text>
                                    </View>
                                )}

                                {/* 上传成功指示器 */}
                                {!image.uploading && image.url && image.url !== image.uri && (
                                    <View style={{
                                        position: 'absolute',
                                        top: 4,
                                        left: 4,
                                        width: 16,
                                        height: 16,
                                        borderRadius: 8,
                                        backgroundColor: '#4CAF50',
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                    }}>
                                        <Text style={{ color: '#fff', fontSize: 10, fontWeight: 'bold' }}>✓</Text>
                                    </View>
                                )}

                                {/* 上传失败重试按钮 */}
                                {!image.uploading && autoUpload && (!image.url || image.url === image.uri) && (
                                    <TouchableOpacity
                                        style={{
                                            position: 'absolute',
                                            bottom: 4,
                                            right: 4,
                                            width: 20,
                                            height: 20,
                                            borderRadius: 10,
                                            backgroundColor: '#FF9800',
                                            justifyContent: 'center',
                                            alignItems: 'center',
                                        }}
                                        onPress={() => retryUpload(image)}
                                    >
                                        <Text style={{ color: '#fff', fontSize: 8, fontWeight: 'bold' }}>↻</Text>
                                    </TouchableOpacity>
                                )}
                            </TouchableOpacity>

                            {/* 删除按钮 */}
                            <TouchableOpacity
                                style={{
                                    position: 'absolute',
                                    top: -8,
                                    right: -8,
                                    width: 24,
                                    height: 24,
                                    borderRadius: 12,
                                    backgroundColor: '#ff4444',
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                    elevation: 3,
                                    shadowColor: '#000',
                                    shadowOffset: { width: 0, height: 2 },
                                    shadowOpacity: 0.25,
                                    shadowRadius: 3.84,
                                    opacity: image.uploading ? 0.5 : 1
                                }}
                                onPress={() => removeImage(index)}
                                disabled={image.uploading}
                            >
                                <Text style={{ color: '#fff', fontSize: 16, fontWeight: 'bold', lineHeight: 20 }}>×</Text>
                            </TouchableOpacity>

                            {/* 文件信息 */}
                            <View style={{
                                position: 'absolute',
                                bottom: 0,
                                left: 0,
                                right: 0,
                                backgroundColor: 'rgba(0,0,0,0.7)',
                                paddingHorizontal: 4,
                                paddingVertical: 2,
                                borderBottomLeftRadius: 8,
                                borderBottomRightRadius: 8,
                            }}>
                                <Text style={{
                                    color: '#fff',
                                    fontSize: 10,
                                    textAlign: 'center',
                                }} numberOfLines={1}>
                                    {image.name}
                                </Text>
                                <Text style={{
                                    color: '#fff',
                                    fontSize: 8,
                                    textAlign: 'center',
                                }}>
                                    {getFileSizeText(image.size)}
                                </Text>
                            </View>
                        </View>
                    ))}
                </View>
            )}

            {/* 上传按钮 */}
            {images.length < maxImages && (
                <TouchableOpacity
                    style={{
                        borderWidth: 2,
                        borderColor: '#ddd',
                        borderStyle: 'dashed',
                        borderRadius: 8,
                        backgroundColor: '#f9f9f9',
                        padding: 20,
                        alignItems: 'center',
                        justifyContent: 'center',
                        marginBottom: 12,
                        minHeight: imageSize,
                    }}
                    onPress={handleImageUpload}
                >
                    <Icon name="add-a-photo" type="material" size={24} color="#666" />
                    <Text style={{
                        fontSize: 14,
                        color: '#666',
                        marginTop: 8,
                        textAlign: 'center',
                    }}>
                        选择图片 ({images.length}/{maxImages})
                    </Text>
                </TouchableOpacity>
            )}

            {/* 提示信息 */}
            <Text style={{
                fontSize: 12,
                color: '#999',
                textAlign: 'center',
                fontStyle: 'italic',
            }}>
                支持 {allowedFormats.join('、')} 格式，
            </Text>
            <Text style={{
                fontSize: 12,
                color: '#999',
                textAlign: 'center',
                fontStyle: 'italic',
            }}>
                最多上传 {maxImages} 张图片，单张不超过 {maxSize} MB
            </Text>

            <ImagePreviewModal
                visible={showImagePreview && showPreview}
                imageUrl={previewImage?.url}
                imageName={previewImage?.name}
                onClose={() => setShowImagePreview(false)}
            />
        </View>
    )
}
